package com.mlnx.weicesugartp;

import com.mlnx.common.utils.MyLog;
import com.mlnx.utils.MD5Util;
import com.mlnx.weicesugartp.enums.Commond;
import com.mlnx.weicesugartp.enums.ResponseStatus;
import com.mlnx.weicesugartp.exception.SugarTpException;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by amanda.shan on 2019/11/26.
 */
@Data
public class SugarPacket {

    MyLog log = MyLog.getLog(getClass());

    private String version;     // 版本号

    private Commond commond;    // 命令

    private String sendNo;      // 发送编号

    private String imei;

    private String imsi;

    private String sn;

    private String unit;    // 单位

    private String productionName;  // 产品名称

    private Long time;      // 时间戳

    private SugarResult sugarResult;

    private List<SugarResult> listSugar;


    public void decode(String msg) {
//       log.info("收到血糖设备消息："+msg);
        if (!checkSum(msg)) {
            throw new SugarTpException("checksum出错");
        }

        // 去掉 {}
        msg = msg.subSequence(1, msg.length() - 1).toString();

        String[] strings = msg.split(":");
        int index = 0;
        version = strings[index++];

        commond = Commond.devoce(strings[index++]);

        switch (commond) {
            case SYN_TIME:
                // {版本号:命令类型:终端发送编号:设备 IMEI 号:时间戳:MD5 效验码
                sendNo = strings[index++];
                imei = strings[index++];
                break;
            case UP_DEVICE_INFO:
                //版本号:命令类型:发送编号:产品名:设备 IMEI 号:设备 IMSI 号: 设备 SN 号:设备单位：时间戳:MD5 效验码
                sendNo = strings[index++];
                productionName = strings[index++];
                imei = strings[index++];
                imsi = strings[index++];
                sn = strings[index++];
                unit = strings[index++];
                time = Long.parseLong(strings[index++]);
                break;
            case UP_SUGAR:
                //版本号:命令类型:终端发送编号:设备 IMEI 号:测试结果：测试样本:测试时间：测试标签：结果是否正常：时间戳:MD5 检验码
                sendNo = strings[index++];
                imei = strings[index++];
                sugarResult = new SugarResult();
                StringBuffer stringBuilder = new StringBuffer(strings[index++]);
                stringBuilder.insert(stringBuilder.length() - 1, ".");
                sugarResult.setResult(stringBuilder.toString());
                sugarResult.setSample(strings[index++]);

                sugarResult.setTestTime(Long.parseLong(strings[index++]));
                String lable = strings[index++];
                sugarResult.setLabel(lable);

                String normal = strings[index++];
                if ("0".equals(normal)) {
                    sugarResult.setNormal("正常");
                } else if ("1".equals(normal)) {
                    sugarResult.setNormal("偏低");
                } else {
                    sugarResult.setNormal("偏高");
                }
                time = Long.parseLong(strings[index++]);
                break;
            case MUTIL_UP_SUGAR:
                sendNo = strings[index++];
                imei = strings[index++];
                listSugar = new ArrayList<>();
                String[] str = msg.split(":S:");
//                String head = str[0];

//                String bottom = str[str.length - 1];
                for (int i = 1; i < str.length - 1; i++) {
                    String[] content = str[i].split(":");
                    SugarResult sugarResult = new SugarResult();
                    StringBuffer builder = new StringBuffer(content[0]);
                    builder.insert(builder.length() - 1, ".");
                    sugarResult.setResult(builder.toString());
                    sugarResult.setSample(content[1]);
                    sugarResult.setTestTime(Long.parseLong(content[2]));
                    sugarResult.setLabel(content[3]);
                    sugarResult.setNormal(content[4]);
                    listSugar.add(sugarResult);
                }
                break;

            default:
                throw new SugarTpException("不支持的设备类型");

        }
    }

    private boolean checkSum(String msg) {
        boolean sign = false;
        // 去掉 {}
        msg = msg.subSequence(1, msg.length() - 1).toString();

        String[] strings = msg.split(":");
        int index = 1;
        commond = Commond.devoce(strings[index++]);
        String secret = "62CYBlgXtoL9lUCB";
        switch (commond) {
            case SYN_TIME:
                // {版本号:命令类型:终端发送编号:设备 IMEI 号:时间戳:MD5 效验码
                sign = verify(strings, secret);
                break;
            case UP_DEVICE_INFO:
                //版本号:命令类型:发送编号:产品名:设备 IMEI 号:设备 IMSI 号: 设备 SN 号:设备单位：时间戳:MD5 效验码
                String sendNum2 = strings[2];
                String deviceIMEI2 = strings[4];
                String time2 = strings[8];
                String verify2 = strings[9];
                String md52 = MD5Util.getStringMD5(sendNum2 + deviceIMEI2 + secret);
                if (md52.equals(verify2)) {
                    sign = true;
                }
                break;
            case UP_SUGAR:
                //版本号:命令类型:终端发送编号:设备 IMEI 号:测试结果：测试样本:测试时间：测试标签：结果是否正常：时间戳:MD5 检验码
                sign = verify(strings, secret);
                break;
            case MUTIL_UP_SUGAR:
                //版本号:命令类型:终端发送编号:设备 IMEI 号:
                //:S:测试结果：测试样本:测试时间：测试标签：结果是否正常：
                //:S:测试结果：测试样本:测试时间：测试标签：结果是否正常：
                //:S:测试结果：测试样本:测试时间：测试标签：结果是否正常：
                //:S:时间戳:MD5 检验码
                sign = verify(strings, secret);
                break;
            case CHANGE_SERVER:
                //版本号:命令类型:服务器信息编号:服务器地址:端口号:时间戳:检验方式
                sign = verify(strings, secret);
                break;

            default:
                break;

        }
        return sign;
    }

    private boolean verify(String[] strings, String secret) {
        String sendNum = strings[2];
        String deviceIMEI = strings[3];
        String verify = strings[strings.length - 1];
        String md5 = MD5Util.getStringMD5(sendNum + deviceIMEI + secret);
        if (md5.equals(verify)) {
            return true;
        }
        return false;
    }

    /**
     * 回复同步时间
     * {版本号#命令类型#终端发送编号#状态字#时间戳}\r\n
     *
     * @return
     */
    public String responseSynTime() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append(version).append("#");
        builder.append(commond.getCode()).append("#");
        builder.append(sendNo).append("#");
        builder.append(ResponseStatus.SUCESS.getCode()).append("#");
        builder.append(System.currentTimeMillis() / 1000);
        builder.append("}\r\n");

        return builder.toString();
    }

    /**
     * 回复登录上传设备信息
     * {版本号#命令类型#终端发送编号#状态字#时间戳}\r\n
     *
     * @return
     */
    public String responseUpDevice() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append(version).append("#");
        builder.append(commond.getCode()).append("#");
        builder.append(sendNo).append("#");
        builder.append(ResponseStatus.SUCESS.getCode()).append("#");
        builder.append(System.currentTimeMillis() / 1000);
        builder.append("}\r\n");

        return builder.toString();
    }

    /**
     * 回复上传血糖数据命令
     * {版本号#命令类型#终端发送编号#状态字#时间戳}\r\n
     *
     * @return
     */
    public String responseUpSugar() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append(version).append("#");
        builder.append(commond.getCode()).append("#");
        builder.append(sendNo).append("#");
        builder.append(ResponseStatus.SUCESS.getCode()).append("#");
        builder.append(System.currentTimeMillis() / 1000);
        builder.append("}\r\n");

        return builder.toString();
    }

    /**
     * 回复上传批量血糖数据命令
     * {版本号#命令类型#终端发送编号#状态字#时间戳}\r\n
     *
     * @return
     */
    public String responseUpMutilSugar() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append(version).append("#");
        builder.append(commond.getCode()).append("#");
        builder.append(sendNo).append("#");
        builder.append(ResponseStatus.SUCESS.getCode()).append("#");
        builder.append(System.currentTimeMillis() / 1000);
        builder.append("}\r\n");

        return builder.toString();
    }


}
